/**
 * Created by zhouli on 18/3/28
 * Email li.zhou@huilianyi.com
 * 未激活的人邀请的弹窗
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import {Modal, Icon, Button, Table, message, Popover} from 'antd';
import PMService from 'containers/enterprise-manage/person-manage/person-manage.service';
import 'styles/enterprise-manage/person-manage/person-manage-components/invite.person.modal.scss';
import menuRoute from 'routes/menuRoute';

class InvitePersonModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inviteModel: false,
      loading: true,
      invating: false,
      params: {
        "keyword": "",
        "departmentOIDs": "",
        "corporationOIDs": "",
        "status": "all"
      },
      //条件下，没有激活的人
      paginationNoActived: {
        page: 0,
        total: 0,
        pageSize: 10,
      },
      dataNoActived: [],//条件下，没有激活的人
      selectedRowKeys: [],///已选择的列表项的key，这个用来记住翻页的
      selectedUserOIDs: [],   //已选择的列表项的OIDs
      columnsNoActived: [
        {
          title: messages('enterprise-manage.key292'/*公司*/),
          key: "companyName",
          dataIndex: 'companyName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key293'/*工号*/),
          key: "employeeID",
          dataIndex: 'employeeID',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key294'/*姓名*/),
          key: "fullName",
          dataIndex: 'fullName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key295'/*部门*/),
          key: "departmentName",
          dataIndex: 'departmentName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key296'/*联系方式*/),
          key: "mobile",
          dataIndex: 'mobile',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
      ]
    };
  }

  componentDidMount() {
    this.setState({
      params: this.props.params
    }, () => {
      this.getPersonListNoActived();
    })
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      params: nextProps.params
    }, () => {
      this.getPersonListNoActived();
    })
  }

  //获取未激活的员工表格
  getPersonListNoActived = () => {
    this.setState({
      loading: true,
    })
    let params = {
      "sort": "status",
      "page": this.state.paginationNoActived.page,
      "size": this.state.paginationNoActived.pageSize,
      "keyword": this.state.params.keyword,
      "departmentOID": this.state.params.departmentOIDs,
      "corporationOID": this.state.params.corporationOIDs,
      "status": this.state.params.status || "all",
      "isInactiveSearch": true
    }
    PMService.searchPersonInDep(params)
      .then((response) => {
        this.setState({
          loading: false,
          dataNoActived: response.data,
          paginationNoActived: {
            page: this.state.paginationNoActived.page,
            pageSize: this.state.paginationNoActived.pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            total: Number(response.headers['x-total-count']),
          }
        }, () => {
          this.refreshRowSelection()
        })
      })
  }
  //分页点击
  onChangePagerNoActived = (pagination, filters, sorter) => {
    this.setState({
      paginationNoActived: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getPersonListNoActived();
    })
  };

  //要求使用的弹窗--start
  showInvite = () => {
    this.setState({
      inviteModel: true
    })
  }
  hideInvite = () => {
    this.setState({
      inviteModel: false
    }, () => {
      this.clearRowSelection();
    })
  }
  //点击确定邀请
  confirmInvite = () => {
    this.setState({
      invating: true
    })
    let selectedUserOIDs = this.state.selectedUserOIDs;
    let selectedRowKeys = this.state.selectedRowKeys;
    if (selectedUserOIDs.length > 0) {
      PMService.inviteUser(selectedUserOIDs)
        .then((res) => {
          message.success(messages('enterprise-manage.key297'/*邀请成功*/));
          this.clearRowSelection();
          this.setState({
            inviteModel: false,
            invating: false
          })
        })
    } else {
      message.warn(messages('enterprise-manage.key298'/*请选择要邀请的员工*/));
    }
  }
  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    this.setState({
      invating: false,
      selectedRowKeys
    });
  };

  onSelectRow = (record, selected) => {
    let temp = this.state.selectedUserOIDs;
    if (selected) {
      temp.push(record.userOID);
    }
    else {
      temp.delete(record.userOID);
    }
    this.setState({
      selectedUserOIDs: temp,
    })
  };

  //全选
  onSelectAllRow = (selected) => {
    let temp = this.state.selectedUserOIDs;
    if (selected) {
      this.state.dataNoActived.map(item => {
        temp.addIfNotExist(item.userOID)
      })
    } else {
      this.state.dataNoActived.map(item => {
        temp.delete(item.userOID)
      })
    }
    this.setState({
      selectedUserOIDs: temp,
    })
  };

  //换页后根据OIDs刷新选择框
  refreshRowSelection() {
    let selectedRowKeys = [];
    this.state.selectedUserOIDs.map(selectedUserOID => {
      this.state.dataNoActived.map((item, index) => {
        if (item.userOID === selectedUserOID)
          selectedRowKeys.push(index);
      })
    });
    this.setState({selectedRowKeys});
  }

  //清空选择框
  clearRowSelection() {
    this.setState({selectedUserOIDs: [], selectedRowKeys: []});
  }

  //修改信息通知渠道
  onUpdateInfo = () => {
    this.context.router.push(menuRoute.getRouteItem('security-setting').url);
  }

  //要求使用的弹窗--end
  render() {
    const {company} = this.props;
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };
    return (
      <div className="invite-person-modal-wrap">
        <div className="person-manage-table-icon-tips">
          <div className="tips-text">
            <Icon type="info-circle" className="info-circle"/>
            <span>
              &nbsp;
              {messages('enterprise-manage.key299'/*当前搜索条件下，有*/)}
              {this.state.paginationNoActived.total}
              {messages('enterprise-manage.key300'/*人尚未激活*/)}
            </span>
            {this.state.paginationNoActived.total > 0 && <span className="tips-inner-btn"
                                                               onClick={this.showInvite}>
              {messages('enterprise-manage.key301'/*邀请使用*/)}
            </span>}
          </div>
        </div>
        <Modal
          closable
          width={800}
          className="pm-invite-person-modal"
          title={<div className="title-wrap">
            <div className="title">{messages('enterprise-manage.key301')/*邀请使用*/}</div>
            <div className="title-tips" onClick={this.onUpdateInfo}>
              {company.noticeType === 1001 && <span>{messages('enterprise-manage.key347')/*将通过邮件通知，*/}</span>}
              {company.noticeType !== 1001 && <span>{messages('enterprise-manage.key348')/*将通过邮件和短信通知，*/}</span>}
              <span>{messages('enterprise-manage.key349')/*修改信息通知渠道*/} &gt;</span>
            </div>
            <div className='clear'/>
          </div>}
          visible={this.state.inviteModel}
          footer={null}
          onCancel={this.hideInvite}
          destroyOnClose={true}
        >
          <div>
            <Table
              loading={this.state.loading}
              dataSource={this.state.dataNoActived}
              columns={this.state.columnsNoActived}
              pagination={this.state.paginationNoActived}
              rowSelection={rowSelection}
              onChange={this.onChangePagerNoActived}
              size="middle"
              bordered
            />
            <div className="no-actived-footer">
              <Button className="cancel"
                      onClick={this.hideInvite}>{messages('common.cancel')}</Button>
              <Button type="primary" loading={this.state.invating}
                      onClick={this.confirmInvite}>{messages('common.ok')}</Button>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

InvitePersonModal.propTypes = {
  params: React.PropTypes.any.isRequired,//请求没激活的人的条件参数
};

InvitePersonModal.defaultProps = {};
InvitePersonModal.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(InvitePersonModal);


